import { combineReducers } from 'redux';
import {
    SELECT_REDDIT, INVALIDATE_REDDIT,
    REQUEST_POSTS, RECEIVE_POSTS,
} from '../actions';

function selectedReddit(state = 'reactjs', action) {
    switch (action.type) {
        case SELECT_REDDIT:
            return action.reddit;
        default:
            return state;
    }
}

function posts(state = {
    isFetching: false,
    didInvalidate: false,
    items: [],
}, action) {
    switch (action.type) {
        case INVALIDATE_REDDIT:
            return Object.assign({}, state, {
                didInvalidate: true,
            });
        case REQUEST_POSTS:
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false,
            });
        case RECEIVE_POSTS:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt,
            });
        default:
            return state;
    }
}

function postsByReddit(state = { }, action) {
    switch (action.type) {
        case INVALIDATE_REDDIT:
        case RECEIVE_POSTS:
        case REQUEST_POSTS:
            return Object.assign({}, state, {
                [action.reddit]: posts(state[action.reddit], action),
            });
        default:
            return state;
    }
}

// combineReducers方法来自redux，它被用来合并多个reducer。这些reducer被合并后，它们所处理的state将会成为state tree中的子节点。

// 因为combineReducers的合并，所以state tree的第一级节点是postsByReddit和selectedReddit：
// 需要对照 Redux DevTools工具查看
const rootReducer = combineReducers({
    postsByReddit,
    selectedReddit,
});

export default rootReducer;


//上面代码做了3件事
// 1. 写了三个reducer。postsByReddit、posts 和 selectedReddit。
// 2. 将 posts 这个 reducer 作为 postsByReddit 返回值中的一个子节点。
// 3. 使用 redux 的 combineReducers 方法把 postsByReddit 和 selectedReddit 合并起来。


